<template>
  <!-- template必须有一个根标签 -->
  <div>
    <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽"> </el-switch>
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-button @click="batchDelete" type="danger">批量删除</el-button>
    <!-- 引入 element-ui 的 tree 控件 -->
    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKeys"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <!-- node：代表tree中的当前节点，data：当前节点的实际 data -->
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">
            Append
          </el-button>
          <el-button type="text" size="mini" @click="edit(data)">
            Edit
          </el-button>
          <el-button v-if="node.childNodes.length == 0" type="text" size="mini" @click="() => remove(node, data)">
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>
    <!-- 编辑框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" :close-on-click-modal="false">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    return {
      draggable: false,
      pCid: [],
      menus: [],
      // 树控件节点数据绑定
      defaultProps: {
        // 子节点
        children: 'children',
        // 节点名称
        label: 'name'
      },
      // 默认展开的多个分组
      expandedKeys: [],
      // 是否展示编辑框
      dialogVisible: false,
      // 新增、编辑的数据对象
      category: { name: '', parentCid: 0, catLevel: 0, showStatus: 1, sort: 0, catId: null, icon: '', productUnit: '' },
      // 编辑框类型 edit/add
      dialogType: '',
      dialogTitle: '',
      maxLevel: 0,
      updateNodes: []
    }
  },
  // 方法集合
  methods: {
    // 获取分类树
    getMenus() {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({ data }) => {
        console.log('成功获取到菜单数据....', data.data);
        this.menus = data.data
      })
    },
    // 点击确定提交数据
    submitData() {
      if (this.dialogType == 'add') {
        this.add()
      }
      if (this.dialogType == 'edit') {
        this.update()
      }
    },
    // 追加按钮
    append(data) {
      console.log('append', data);
      this.dialogType = 'add';
      this.dialogTitle = '新增分类';
      this.dialogVisible = true;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      // 重置要填写的数据
      this.category.sort = 0;
      this.category.showStatus = 1;
      this.category.name = '';
      this.category.catId = null;
      this.category.icon = '';
      this.category.productUnit = ''
    },
    // 新增
    add() {
      console.log('要提交的分类数据：', this.category);
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        this.$message({
          message: '菜单保存成功',
          type: 'success'
        });
        this.dialogVisible = false;
        this.getMenus();
        this.expandedKeys = [this.category.parentCid]
      })
    },
    // 批量保存
    batchSave() {
      this.$http({
        url: this.$http.adornUrl('/product/category/update/drag'),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        this.$message({
          message: '菜单顺序修改成功',
          type: 'success'
        });
        this.getMenus();
        this.expandedKeys = this.pCid;
        // 清空临时变量
        this.updateNodes = [];
        this.maxLevel = 0
        // this.pCid = 0
      })
    },
    // 编辑按钮
    edit(data) {
      console.log('要修改的数据', data);
      this.dialogType = 'edit';
      this.dialogTitle = '修改分类';
      this.dialogVisible = true;
      // 回显数据
      // 发送请求获取当前节点最新信息
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get'
      }).then(({ data }) => {
        console.log('要回显的数据', data);
        this.category.name = data.data.name;
        this.category.catId = data.data.catId;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.category.parentCid = data.data.parentCid
      })
    },
    // 修改
    update() {
      var { catId, name, icon, productUnit } = this.category;
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        data: this.$http.adornData({ catId, name, icon, productUnit }, false)
      }).then(({ data }) => {
        this.$message({
          message: '菜单修改成功',
          type: 'success'
        });
        this.dialogVisible = false;
        this.getMenus();
        this.expandedKeys = [this.category.parentCid]
      })
    },
    // 删除按钮
    remove(node, data) {
      console.log('remove', node, data);
      // 误操作确认
      this.$confirm(`是否删除【${data.name}】菜单?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          var ids = [data.catId];
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            this.$message({
              message: '菜单删除成功',
              type: 'success'
            });
            this.getMenus();
            this.expandedKeys = [node.parent.data.catId]
          })
        })
        .catch(() => {})
    },
    // 批量删除
    batchDelete() {
      // let checkedNodes = this.$refs.menuTree.getCheckedNodes()
      let checkedNodes = this.$refs.menuTree.getCheckedKeys();
      console.log('被选中的节点', checkedNodes);
      // 误操作确认
      this.$confirm(`是否批量删除【${checkedNodes}】菜单?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'post',
            data: this.$http.adornData(checkedNodes, false)
          }).then(({ data }) => {
            this.$message({
              message: '菜单批量删除成功',
              type: 'success'
            });
            this.getMenus()
            // this.expandedKeys = [node.parent.data.catId]
          })
        })
        .catch(() => {})
    },
    // 判定是否可以被拖拽到指定位置
    allowDrop(draggingNode, dropNode, type) {
      // 被拖动的节点及其子节点的层数和目标节点的层数之和不能大于3
      // 1. 被拖动节点的层数
      console.log('allowDrop', draggingNode, dropNode, type);
      this.countNodeLevel(draggingNode);
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
      console.log('深度', deep);
      // 2. 目标节点的层数 dropNode.level/dropNode.parent.level
      if (type == 'inner') {
        return deep + dropNode.level <= 3
      } else {
        return deep + dropNode.parent.level <= 3
      }
    },
    countNodeLevel(node) {
      // 找到所有子节点，求出最大深度
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level
          }
          this.countNodeLevel(node.childNodes[i])
        }
      }
    },
    // 监听拖拽成功后的事件
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log('handleDrop: ', draggingNode, dropNode, dropType);
      // 当前节点的父节点id，目标节点前后的话，目标节点的父id
      let pCid = 0;
      let siblings = null;
      if (dropNode == 'inner') {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes
      } else {
        pCid = dropNode.parent.data.catId == undefined ? 0 : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes
      }

      this.pCid.push(pCid);

      // 当前节点的顺序
      for (let i = 0; i < siblings.length; i++) {
        if (draggingNode.data.catId == siblings[i].data.catId) {
          // 默认层级
          let catLevel = draggingNode.level;
          // 判断当前节点层级是否发生变化，如果变化，子节点层级需要变化
          if (siblings[i].level != draggingNode.level) {
            // 当前节点层级发生变化，当前节点的最新层级
            catLevel = siblings[i].level;
            // 修改子节点的 level
            this.updateChildNodeLevel(siblings[i])
          }
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i, parentCid: pCid, catLevel: catLevel })
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i })
        }
      }
      console.log('updateNodes', this.updateNodes)
    },
    // 递归修改所有子节点的层级
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          this.updateNodes.push({ catId: node.childNodes[i].data.catId, catLevel: node.childNodes[i].level });
          if (node.childNodes[i].childNodes.length > 0) {
            this.updateChildNodeLevel(node.childNodes[i])
          }
        }
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getMenus()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style></style>
